<?php
namespace app\modules\common\filters;

use app\modules\common\components\Common;
use app\modules\v1\verify\LoginVerify;
use Exception;
use stdClass;
use Yii;
use yii\base\ActionFilter;

class LoginFilter extends ActionFilter
{
    public function beforeAction($action)
    {
        try {
            $request = yii::$app->request;
            $headers = $request->getHeaders();
            $model = new LoginVerify();
            $model->scenario = 'islogin';
            $model->xEcsU = $headers['X-ECS-U'] ?? "";
            $model->xEcsS = $headers['X-ECS-S'] ?? "";

            if ($model->validate()) {
                $userInfo = json_decode(base64_decode($headers['X-ECS-U']), true);
                yii::$app->request->setQueryParams([
                    'userInfo'=> $userInfo
                ]);
                return parent::beforeAction($action); // TODO: Change the autogenerated stub
            } else {
                $messageArr = Common::errorMessage($model);
                throw new Exception($messageArr['desc'], $messageArr['code']);
            }
        } catch (Exception $exception) {
            $checkReturn = Common::codeReturn(new stdClass(), $exception->getCode(), $exception->getMessage());
            $response = yii::$app->getResponse();
            $response->setStatusCode(200);
            $response->format = \yii\web\Response::FORMAT_JSON;
            $response->data = $checkReturn;
            return false;
        }
    }
}
